// Lindsay Gilmour
// Adam Lusch
// Dan Niceswanger
//
// Computer Graphics Project 1:
// Asteroids!
// A Tribute

#include "Bullet.h"

const float32 Bullet::halfWidth = 0.15f;

Bullet::Bullet(b2World* w, float32 x, float32 y, float32 angle, const b2Vec2& vel, int32 mag)
	: Thing(w, 1, mag)
{
	ttl = 60 * 2; // 2 seconds at 60 fps
	
	b2BodyDef bodyDef;
	bodyDef.position.Set(x, y);
	bodyDef.angle = angle;
	bodyDef.angularDamping = 10.0;
	body = world->CreateBody(&bodyDef);

	glNewList(baseDisplayList, GL_COMPILE);
	glBegin(GL_LINE_LOOP);
	
	b2PolygonDef squareDef;
	squareDef.vertices[0] = b2Vec2(halfWidth, halfWidth);
	squareDef.vertices[1] = b2Vec2(-halfWidth, halfWidth);
	squareDef.vertices[2] = b2Vec2(-halfWidth, -halfWidth);
	squareDef.vertices[3] = b2Vec2(halfWidth, -halfWidth);
	
	glVertex2f(squareDef.vertices[0].x, squareDef.vertices[0].y);
	glVertex2f(squareDef.vertices[1].x, squareDef.vertices[1].y);
	glVertex2f(squareDef.vertices[2].x, squareDef.vertices[2].y);
	glVertex2f(squareDef.vertices[3].x, squareDef.vertices[3].y);
		
	squareDef.vertexCount = 4;
	squareDef.density = 5.0f;
	squareDef.friction = 0.0f;
	squareDef.restitution = 0.995f;
	squareDef.userData = this;
	body->CreateShape(&squareDef);
	updateBoundingRadius(squareDef);

	glEnd();
	glEndList();

	body->SetMassFromShapes();
	
	float32 fx = 10.0f * cos(angle);
	float32 fy = 10.0f * sin(angle);
	
	body->SetLinearVelocity(vel);
	
	body->ApplyImpulse(b2Vec2(fx, fy), body->GetWorldPoint(b2Vec2(0.0, 0.0)));
}

Bullet::~Bullet()
{
}

int32 Bullet::getTTL() const
{
	return ttl;
}

void Bullet::draw()
{
	--ttl;
	
	b2Vec2 position = body->GetPosition();
	float32 angle = body->GetAngle();

	glPushMatrix();
	
	glTranslatef(position.x, position.y, 0.0);
	glRotatef(angle*180.0/M_PI, 0.0, 0.0, 1.0);
	
	glLineWidth(2);
	
	glColor3f(0.0f, 1.0f, 0.5f);
	glCallList(baseDisplayList);
	
	glPopMatrix();
}
